<?php

/*
 * File Writer Class
 * ===============================================
 * Date: March 17th, 2012
 * Created By: Integration Team
 * ===============================================
 */

/**
 * contains the necessary functionality to write the output file
 */
class FileWriter{
    
    protected $fileName;
    protected $filePath;
    protected $mode;
    protected $handle;

    public function __construct($FileName = '', $FilePath = '', $mode = 'a', $delete_first = TRUE) {
        //@param $mode signifies if the file needs to be overwritten or appended to
        //@param $delete_first specifies whether the file needs to be deleted before recreating and opening
        
         $this->fileName = $FileName;
         $this->filePath = rtrim(rtrim($FilePath, "/"),"\\").DIRECTORY_SEPARATOR; //Needed in case the Directory Separator is specified in the end 
         $this->mode = $mode;
         //If the directory doesn't exist - create it 
         if(!is_dir($this->filePath)) mkdir ($this->filePath);
         //If the file needs to be deleted first 
            if($delete_first == TRUE)
            {
                $this->unlink_file ();
            }
                
         $this->open_for_writing();
         
    }
    protected function unlink_file()
    {
        //Deletes the specified file 
        if (file_exists($this->filePath.$this->fileName)) 
        {
                if(!unlink($this->filePath.$this->fileName)) 
                {
                    throw new customException("Could not delete FileWriter file",1);
                }
            
        }
    }
    protected function open_for_writing()
    {
           if(!$this->handle = fopen($this->filePath.$this->fileName, $this->mode))
           {
                throw new customException('Could not open File for writing');
           }
               
        
    }
    public function close_handle()
    {
        if(isset($this->handle))
        {
             fclose($this->handle);
        }   
    }
    public function write($string)
    {
        try 
        {
        fwrite($this->handle, $string);
        }
        catch (Exception $e)
        {
            echo $e->getMessage().$e->getTraceAsString();
            exit(1);
        }
        
    }
}
?>
